package com.wizardOther.Items;

import Validator.Validator;
import com.appclient.DaoInstanceEnum;
import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.DAO.DaoImpl;
import com.carpark.ejb.Model.TarrifsModel;
import com.table.TariffTableController;
import com.wizardOther.OtherControlledScreen;
import com.wizardOther.OtherScreensController;
import com.wizardOther.OtherScreensFramework;
import java.io.IOException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;

/**
 *
 * @author Vi
 */
public class AddNewTariffController extends ValidationForm implements Initializable, OtherControlledScreen {

    private OtherScreensController myController;
    @FXML
    private Button addTariff;
    @FXML 
    private Button cancel;
    @FXML
    private Button select;
    @FXML
    private TextField tarrifName;
    @FXML
    private TextField issueDate;
    @FXML
    private TextField endDate;
    @FXML
    private TextField durationTime;
    @FXML
    private TextField Rank;
    @FXML
    private ComboBox carType;
    @FXML
    private TextArea comment;
    @FXML
    private Label errorTarrifName;
    @FXML
    private Label errorIssueDate;
    @FXML
    private Label errorEndDate;
    @FXML
    private Label errorDurationTime;
    @FXML
    private Label errorRank;
    @FXML
    private Label errorCartType;
    @FXML
    private Label errorComment;
    
    private Integer selectedTarrif;
    private TariffTableController controller;
   

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        inputs.clear();
        inputs.add(tarrifName);
        inputs.add(issueDate);
        inputs.add(endDate);
        inputs.add(durationTime);
        inputs.add(Rank);
        inputs.add(carType);
        inputs.add(comment);

        labels.clear();
        labels.add(errorTarrifName);
        labels.add(errorIssueDate);
        labels.add(errorEndDate);
        labels.add(errorDurationTime);
        labels.add(errorRank);
        labels.add(errorCartType);
        labels.add(errorComment);
    }
    
    
    
    @FXML
    private void handleButtonAction(ActionEvent event) {
        if(event.getSource()==addTariff){
            validateForm();
        }
        if(event.getSource()==cancel){
            clearForm();
        }
        
        if(event.getSource()==select){
            showTariffTableDialog();
            
            selectedTarrif=controller.getSelectedTariff();
            
            if(this.selectedTarrif!=null){
                loadData(selectedTarrif);
            }
            
        }
    }
    
     private boolean showTariffTableDialog() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("tariffTable.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Wybierz pojazd");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);

            controller = loader.getController();
            controller.setDialogStage(dialogStage);

            dialogStage.showAndWait();

            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    private void loadData(Integer selectedT) {
        TarrifsModel tariff = DaoInstanceEnum.INSTANCE.getDao().getTarrifsById(selectedT);
        
        if (tariff != null) {
            this.tarrifName.setText(tariff.getName());
            this.issueDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(tariff.getIssueDate()));
            this.endDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(tariff.getEndDate()));
            this.durationTime.setText(tariff.getDurationTime());
            this.Rank.setText(String.valueOf(tariff.getRank()));
            this.carType.setValue(tariff.getCarType().toString());
            this.comment.setText(tariff.getComments());
        }
    }

    
    private void validateForm() {
        makeList(7);
        takeDateFromForm();
        setWrongTextFields(correctField);
        
        
        printValidator(correctField);
        if(isCorrect(correctField)){
          
            List<Boolean> goodRecord = Validator.checkTarrifCheckList(getTariff());
            setWrongTextFields(goodRecord);
            
            if(isCorrect(goodRecord)){
               
                try{
                      DAO dao = DaoInstanceEnum.INSTANCE.getDao();
                      if(selectedTarrif!=null){
                          TarrifsModel tarrif = getTariff();
                          tarrif.setTarrifId(selectedTarrif);
                           dao.updateTarrif(tarrif);
                           createPopup("Zapisano zmiany!");
                      }
                      else{
                           dao.addTarrif(getTariff());
                           createPopup("Dodano nową taryfę!");
                           this.selectedTarrif=null;
                      }
                     clearForm();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
       }
    }
    
    private void takeDateFromForm(){
        checkString(this.tarrifName.getText(),0);
        checkDate(this.issueDate.getText(),1);
        checkDate(this.endDate.getText(),2);
        checkString(this.durationTime.getText(),3);
        checkDouble(this.Rank.getText(),4);
        checkString(renameCarType((String)this.carType.getValue()),5);
        checkComments(this.comment.getText(),6);
    }
    
    
    @FXML
    private void goToMain(java.awt.event.ActionEvent event) {
        myController.setScreen(OtherScreensFramework.OTHER_BUTTONS_PANEL);
    }
    
   
    private TarrifsModel getTariff() {
        String name = this.tarrifName.getText();
        String startDate = this.issueDate.getText();
        String endDate = this.endDate.getText();
        String duratiomTime = this.durationTime.getText();
        String rank = this.Rank.getText();
        String carType = renameCarType((String) this.carType.getValue());
        String comments = this.comment.getText();
        TarrifsModel tariff = new TarrifsModel(name, Date.valueOf(startDate), Date.valueOf(endDate), duratiomTime, Double.parseDouble(rank), carType);
        
        tariff.setComments(comments);

        return tariff;
    }  
    
    
    @Override
    public void setScreenParent(OtherScreensController screenParent) {
        myController = screenParent;
    }

    private void clearForm(){
        this.selectedTarrif=null;
        this.tarrifName.setText("");
        this.issueDate.setText("");
        this.endDate.setText("");
        this.durationTime.setText("");
        this.Rank.setText("");
        this.carType.setValue("Wybierz typ pojazdu");
        this.comment.setText("");
          makeList(7);
         setWrongTextFields(correctField);
    }
}
